package com.example.security;

import cn.hutool.json.JSONUtil;
import com.example.domain.vo.Result;
import com.example.utils.RedisClient;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 注销成功后的处理器
 */
@RequiredArgsConstructor
@Component
public class LogoutStatusSuccessHandler implements LogoutSuccessHandler {

    private final RedisClient redisClient;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getHeader("token");
        //判断是否存在token
        if(StringUtils.hasText(token)){
            //redis删除token
            String key="login:token:"+token;
            redisClient.del(key);
            }
        //返回注销成功的提示
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        Result result = Result.ok("注销成功");
        String json = JSONUtil.toJsonStr(result);
        response.getWriter().print(json);
    }
}
